﻿using System;
using System.Windows;
using System.Windows.Threading;
using PeoplesJukebox.Web.Entities;
using PeoplesJukebox.Web.Enums;

namespace PeoplesJukebox.Web.Pages
{
    /// <summary>
    /// Page for users to confirm or reject selecting a track
    /// </summary>
    /// <remarks>
    /// On confirmation, uses a timer to pause for a short period, to
    /// deter users form making multiple selections
    /// </remarks>
    public partial class ConfirmTrackSelection : PageBase
    {
        private int _tickCount = 0;
        private DispatcherTimer _waitTimer;

        private MediaItem SelectedItem
        {
            get { return (MediaItem)this.DataContext; }
        }

        /// <summary>
        /// Returns the page type
        /// </summary>
        public override PageType PageType
        {
            get { return PageType.ConfirmTrackSelection; }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public ConfirmTrackSelection()
        {
            InitializeComponent();
            _waitTimer = new DispatcherTimer();
            _waitTimer.Interval = new TimeSpan(0, 0, 0, 2, 500);
            _waitTimer.Tick += new EventHandler(ShowProgress);
        }

        /// <summary>
        /// Resets the page state
        /// </summary>
        public override void Reset()
        {
            base.Reset();
            this.txtYes.Text = string.Format("Add \"{0}\"", this.SelectedItem.Name);
            this.panelConfirm.Visibility = Visibility.Visible;
            this.panelComplete.Visibility = Visibility.Collapsed;
            this.progressBar.Visibility = Visibility.Visible;
            this.txtComplete.Text = "Adding track to queue...";
        }

        private void btnYes_Click(object sender, RoutedEventArgs e)
        {
            this.PlayerServiceClient.Queue(this.SelectedItem.Id);
            //pretend something is happening to deter repeat selection:
            this.panelConfirm.Visibility = Visibility.Collapsed;
            this.panelComplete.Visibility = Visibility.Visible;
            _waitTimer.Start();
        }

        private void btnNo_Click(object sender, RoutedEventArgs e)
        {
            this.Cancel();
        }

        private void ShowProgress(object sender, EventArgs e)
        {
            if (this._tickCount == 0)
            {
                this.progressBar.Visibility = Visibility.Collapsed;
                this.txtComplete.Text = "Track added. Thank you!";
                this._tickCount++;
            }
            else
            {
                this._waitTimer.Stop();
                this._tickCount = 0;
                this.Completed(PageType.Home);
            }
        }
    }
}